package org.jeecg.modules.order.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itextpdf.text.DocumentException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.chanp.entity.KuybChanp;
import org.jeecg.modules.chanp.service.IKuybChanpService;
import org.jeecg.modules.chanpSku.entity.KuybChanpSku;
import org.jeecg.modules.chanpSku.service.IKuybChanpSkuService;
import org.jeecg.modules.chexkModel.entity.KuybChexkModel;
import org.jeecg.modules.chexkModel.service.IKuybChexkModelService;
import org.jeecg.modules.ctiy.entity.KuybCtiy;
import org.jeecg.modules.ctiy.service.IKuybCtiyService;
import org.jeecg.modules.jiasj.entity.KuybJiasj;
import org.jeecg.modules.jiasj.service.IKuybJiasjService;
import org.jeecg.modules.order.entity.KuybOrder;
import org.jeecg.modules.order.entity.KuybOrderChanp;
import org.jeecg.modules.order.entity.KuybOrderPayment;
import org.jeecg.modules.order.entity.KuybOrderPolicy;
import org.jeecg.modules.order.service.IKuybOrderChanpService;
import org.jeecg.modules.order.service.IKuybOrderPaymentService;
import org.jeecg.modules.order.service.IKuybOrderPolicyService;
import org.jeecg.modules.order.service.IKuybOrderService;
import org.jeecg.modules.order.vo.Hebzp;
import org.jeecg.modules.order.vo.KuybOrderPage;
import org.jeecg.modules.orderShenh.entity.KuybOrderShenh;
import org.jeecg.modules.orderShenh.service.IKuybOrderShenhService;
import org.jeecg.modules.taoc.entity.KuybTaoc;
import org.jeecg.modules.taoc.service.IKuybTaocService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 订单
 * @Author: jeecg-boot
 * @Date: 2021-09-09
 * @Version: V1.0
 */
@Api(tags = "订单")
@RestController
@RequestMapping("/order/kuybOrder")
@Slf4j
public class KuybOrderController {
    @Autowired
    IKuybChexkModelService kuybChexkModelService;

    @Autowired
    IKuybJiasjService kuybJiasjService;

    @Autowired
    private IKuybOrderService kuybOrderService;
    @Autowired
    private IKuybOrderPaymentService kuybOrderPaymentService;
    @Autowired
    private IKuybOrderPolicyService kuybOrderPolicyService;
    @Autowired
    private IKuybOrderChanpService kuybOrderChanpService;

    @Autowired
    IKuybTaocService kuybTaocService;

    @Autowired
    IKuybChanpService kuybChanpService;

    @Autowired
    IKuybOrderShenhService kuybOrderShenhService;

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    IKuybChanpSkuService kuybChanpSkuService;

    @Autowired
    IKuybCtiyService kuybCtiyService;

    @SneakyThrows
    @GetMapping(value = "/getYewysd")
    public Result<?> getYewysd(String yewysd) {
        List<Map<String, Object>> result = new ArrayList();

        ClassPathResource classPathResource = new ClassPathResource("area/province.json");
        InputStream inputStream = classPathResource.getInputStream();
        String tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONArray jsonArray_province = JSONArray.parseArray(tmp);

        classPathResource = new ClassPathResource("area/city.json");
        inputStream = classPathResource.getInputStream();
        tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONObject jsonObject_city = JSONObject.parseObject(tmp);

        classPathResource = new ClassPathResource("area/county.json");
        inputStream = classPathResource.getInputStream();
        tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONObject jsonObject_county = JSONObject.parseObject(tmp);

        List list = new ArrayList();

        // 省
        jsonArray_province.forEach(item -> {
            JSONObject jsonObject = (JSONObject) item;
            Map<String, Object> map = new HashMap<>();
            map.put("text", jsonObject.getString("name"));
            map.put("value", jsonObject.getString("id"));

            // 市
            List<Map<String, Object>> children = new ArrayList();
            jsonObject_city.getJSONArray(jsonObject.getString("id")).forEach(item2 -> {
                JSONObject jsonObject2 = (JSONObject) item2;
                Map<String, Object> map2 = new HashMap<>();
                map2.put("text", jsonObject2.getString("name"));
                map2.put("value", jsonObject2.getString("id"));

                if(jsonObject2.getString("id").equals(yewysd)) {
                    list.add(jsonObject.getString("id"));
                    list.add(jsonObject2.getString("id"));
                }
            });
        });

        return Result.OK(list);
    }

    @SneakyThrows
    @GetMapping(value = "/genCityCode")
    public Result<?> genCityCode() {
        List<Map<String, Object>> result = new ArrayList();

        ClassPathResource classPathResource = new ClassPathResource("area/province.json");
        InputStream inputStream = classPathResource.getInputStream();
        String tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONArray jsonArray_province = JSONArray.parseArray(tmp);

        classPathResource = new ClassPathResource("area/city.json");
        inputStream = classPathResource.getInputStream();
        tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONObject jsonObject_city = JSONObject.parseObject(tmp);

        classPathResource = new ClassPathResource("area/county.json");
        inputStream = classPathResource.getInputStream();
        tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONObject jsonObject_county = JSONObject.parseObject(tmp);

        // 省
        jsonArray_province.forEach(item -> {
            JSONObject jsonObject = (JSONObject) item;
            Map<String, Object> map = new HashMap<>();
            map.put("text", jsonObject.getString("name"));
            map.put("value", jsonObject.getString("id"));

            // 市
            List<Map<String, Object>> children = new ArrayList();
            jsonObject_city.getJSONArray(jsonObject.getString("id")).forEach(item2 -> {
                JSONObject jsonObject2 = (JSONObject) item2;
                Map<String, Object> map2 = new HashMap<>();
                map2.put("text", jsonObject2.getString("name"));
                map2.put("value", jsonObject2.getString("id"));

                KuybCtiy kuybCtiy = new KuybCtiy();

                kuybCtiy.setParentId(jsonObject.getString("id"));
                kuybCtiy.setParentName(jsonObject.getString("name"));

                kuybCtiy.setChengsbm(jsonObject2.getString("id"));
                kuybCtiy.setChengsmc(jsonObject2.getString("name"));

                kuybCtiyService.save(kuybCtiy);
            });
        });

        return Result.OK();
    }

    // 匹配全国城市售卖的产品
    @SneakyThrows
    @GetMapping(value = "/bianlCityGenProduct")
    public Result<?> bianlCityGenProduct() {
        kuybChanpSkuService.remove(null);

        ClassPathResource classPathResource = new ClassPathResource("area/province.json");
        InputStream inputStream = classPathResource.getInputStream();
        String tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONArray jsonArray_province = JSONArray.parseArray(tmp);

        classPathResource = new ClassPathResource("area/city.json");
        inputStream = classPathResource.getInputStream();
        tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONObject jsonObject_city = JSONObject.parseObject(tmp);

        classPathResource = new ClassPathResource("area/county.json");
        inputStream = classPathResource.getInputStream();
        tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONObject jsonObject_county = JSONObject.parseObject(tmp);

        // 省
        jsonArray_province.forEach(item -> {
            JSONObject jsonObject = (JSONObject) item;
            Map<String, Object> map = new HashMap<>();
            map.put("text", jsonObject.getString("name"));
            map.put("value", jsonObject.getString("id"));

            // 市
            List<Map<String, Object>> children = new ArrayList();
            jsonObject_city.getJSONArray(jsonObject.getString("id")).forEach(item2 -> {
                JSONObject jsonObject2 = (JSONObject) item2;
                Map<String, Object> map2 = new HashMap<>();
                map2.put("text", jsonObject2.getString("name"));
                map2.put("value", jsonObject2.getString("id"));

                List list = new ArrayList();
                KuybChanpSku kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setId(jsonObject2.getString("id"));
                kuybChanpSku.setSkuname(jsonObject2.getString("name")); // 城市，例如北京市
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("日产安芯无忧（三大件）尊享版");
                kuybChanpSku.setSkuvalue("1461620634223661057");
                kuybChanpSku.setNengylx("1");
                kuybChanpSku.setSequence(1f);
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("日产安享无忧（六大件）尊享版");
                kuybChanpSku.setSkuvalue("1461620861395554305");
                kuybChanpSku.setNengylx("1");
                kuybChanpSku.setSequence(1f);
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("畅想无忧（拾大件）尊享版");
                kuybChanpSku.setSkuvalue("1458123772344778753");
                kuybChanpSku.setNengylx("1");
                kuybChanpSku.setSequence(1f);
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("纯电无忧（七大系统）尊享版");
                kuybChanpSku.setSkuvalue("1453631319185088513");
                kuybChanpSku.setNengylx("3");
                kuybChanpSku.setSequence(1f);
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("混动无忧（九大系统）尊享版");
                kuybChanpSku.setSkuvalue("1453631423543566337");
                kuybChanpSku.setNengylx("2");
                kuybChanpSku.setSequence(1f);
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("安芯无忧（三大件）尊享版");
                kuybChanpSku.setSkuvalue("1435893538614788097");
                kuybChanpSku.setNengylx("1");
                kuybChanpSku.setSequence(1f);
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("安享无忧（六大件）尊享版");
                kuybChanpSku.setSkuvalue("1435812402857308161");
                kuybChanpSku.setNengylx("1");
                kuybChanpSku.setSequence(1f);
                list.add(kuybChanpSku);

                // 暂时只有成都和哈尔滨开整车产品
//                kuybChanpSku = new KuybChanpSku();
//                kuybChanpSku.setParentid(jsonObject2.getString("id"));
//                kuybChanpSku.setLevel(1);
//                kuybChanpSku.setSkuname("安全无忧（整车）尊享版");
//                kuybChanpSku.setSkuvalue("1435812347907731458");
//                kuybChanpSku.setNengylx("1");
//                kuybChanpSku.setSequence(1f);
//                list.add(kuybChanpSku);

                // 低配产品
                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("日产安芯无忧（三大件）标准版");
                kuybChanpSku.setSkuvalue("1461620634223661056");
                kuybChanpSku.setNengylx("1");
                kuybChanpSku.setSequence(2f);
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("日产安享无忧（六大件）标准版");
                kuybChanpSku.setSkuvalue("1461620861395554306");
                kuybChanpSku.setNengylx("1");
                kuybChanpSku.setSequence(2f);
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("畅想无忧（拾大件）标准版");
                kuybChanpSku.setSkuvalue("1458123772344778754");
                kuybChanpSku.setNengylx("1");
                kuybChanpSku.setSequence(2f);
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("纯电无忧（七大系统）标准版");
                kuybChanpSku.setSkuvalue("1453631319185088514");
                kuybChanpSku.setNengylx("3");
                kuybChanpSku.setSequence(2f);
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("混动无忧（九大系统）标准版");
                kuybChanpSku.setSkuvalue("1453631423543566338");
                kuybChanpSku.setNengylx("2");
                kuybChanpSku.setSequence(2f);
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("安芯无忧（三大件）标准版");
                kuybChanpSku.setSkuvalue("1435893538614788098");
                kuybChanpSku.setNengylx("1");
                kuybChanpSku.setSequence(2f);
                list.add(kuybChanpSku);

                kuybChanpSku = new KuybChanpSku();
                kuybChanpSku.setParentid(jsonObject2.getString("id"));
                kuybChanpSku.setLevel(1);
                kuybChanpSku.setSkuname("安享无忧（六大件）标准版");
                kuybChanpSku.setSkuvalue("1435812402857308162");
                kuybChanpSku.setNengylx("1");
                kuybChanpSku.setSequence(2f);
                list.add(kuybChanpSku);

                // 暂时只有成都和哈尔滨开整车产品
//                kuybChanpSku = new KuybChanpSku();
//                kuybChanpSku.setParentid(jsonObject2.getString("id"));
//                kuybChanpSku.setLevel(1);
//                kuybChanpSku.setSkuname("安全无忧（整车）标准版");
//                kuybChanpSku.setSkuvalue("1435812347907731459");
//                kuybChanpSku.setNengylx("1");
//                kuybChanpSku.setSequence(2f);
//                list.add(kuybChanpSku);

                kuybChanpSkuService.saveBatch(list);

            });
        });

        return Result.OK();
    }

    @PutMapping(value = "/yewyUploadHebzp")
    public Result<?> yewyUploadHebzp(@RequestBody Hebzp hebzp) {
        KuybOrder kuybOrder = kuybOrderService.getOne(new LambdaQueryWrapper<KuybOrder>().eq(KuybOrder::getDingdbh, hebzp.getDingdbh()), false);
        if(kuybOrder != null) {
            List<KuybOrderPolicy> kuybOrderPolicyList = kuybOrderPolicyService.selectByMainId(kuybOrder.getId());
            if(kuybOrderPolicyList != null && kuybOrderPolicyList.size() > 0) {
                KuybOrderPolicy kuybOrderPolicy = kuybOrderPolicyList.get(0);
                if(kuybOrderPolicy != null) {
                    BeanUtils.copyProperties(hebzp, kuybOrderPolicy);
                    kuybOrderPolicyService.updateById(kuybOrderPolicy);

                    return Result.OK();
                }
            }
        }

        return Result.error("异常");
    }

    @GetMapping(value = "/getOrderByCheph")
    public Result<?> getOrderByCheph(String cheph) {
        KuybOrderPolicy kuybOrderPolicy = kuybOrderPolicyService.getOne(new LambdaQueryWrapper<KuybOrderPolicy>()
                .orderByDesc(KuybOrderPolicy::getCreateTime)
                .eq(KuybOrderPolicy::getBebxcph, cheph), false);

        if(kuybOrderPolicy != null)
            return Result.OK(kuybOrderPolicy);
        else
            return Result.error("没找到对应的数据");
    }

    @Scheduled(fixedRate = 6000 * 3)
    void onTimeClearUnPayOrder() {
        System.out.println("定时任务");
        List<KuybOrder> list = kuybOrderService.list(new LambdaQueryWrapper<KuybOrder>().eq(KuybOrder::getDingdzt, 0));
        List<String> batchDeleteList = new ArrayList<>();
        list.forEach(item -> {
            long betweenHour = DateUtil.between(item.getCreateTime(), new Date(), DateUnit.HOUR);
            if(betweenHour > 1)
                batchDeleteList.add(item.getId());
        });

        if(batchDeleteList.size() > 0) {
            if (kuybOrderService.removeByIds(batchDeleteList))
                log.info("批量删除未支付订单成功");
            else
                log.error("批量删除未支付订单失败");
        }
    }

    @GetMapping(value = "/refundList")
    public Result<?> refundList(KuybOrder kuybOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<KuybOrder> queryWrapper = QueryGenerator.initQueryWrapper(kuybOrder, req.getParameterMap());
        queryWrapper.eq("dingdzt", 2);

        Page<KuybOrder> page = new Page<KuybOrder>(pageNo, pageSize);
        IPage<KuybOrder> pageList = kuybOrderService.page(page, queryWrapper);
        pageList.getRecords().forEach(item -> {
            List<KuybOrderChanp> kuybOrderChanpList = kuybOrderChanpService.selectByMainId(item.getId());
            item.setKuybOrderChanpList(kuybOrderChanpList);

            if (kuybOrderChanpList != null && kuybOrderChanpList.size() > 0) {
                List<KuybTaoc> kuybTaocList = kuybTaocService.list(new LambdaQueryWrapper<KuybTaoc>().eq(KuybTaoc::getSuoscp, kuybOrderChanpList.get(0).getChanpid()));
                item.setKuybTaocList(kuybTaocList);
            }

            List<KuybOrderPolicy> kuybOrderPolicyList = kuybOrderPolicyService.selectByMainId(item.getId());
            item.setKuybOrderPolicyList(kuybOrderPolicyList);

            List<KuybOrderPayment> list = kuybOrderPaymentService.selectByMainId(item.getId());
            if (list != null && list.size() > 0) {
                KuybOrderPayment kuybOrderPayment = list.get(0);

            }
        });

        return Result.OK(pageList);
    }

    @SneakyThrows
    @Cacheable(value = "getShengsqxData")
    @GetMapping(value = "/getShengsqxData")
    public Result<?> getShengsqxData() {
        List<Map<String, Object>> result = new ArrayList();

        ClassPathResource classPathResource = new ClassPathResource("area/province.json");
        InputStream inputStream = classPathResource.getInputStream();
        String tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONArray jsonArray_province = JSONArray.parseArray(tmp);

        classPathResource = new ClassPathResource("area/city.json");
        inputStream = classPathResource.getInputStream();
        tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONObject jsonObject_city = JSONObject.parseObject(tmp);

        classPathResource = new ClassPathResource("area/county.json");
        inputStream = classPathResource.getInputStream();
        tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONObject jsonObject_county = JSONObject.parseObject(tmp);

        // 省
        jsonArray_province.forEach(item -> {
            JSONObject jsonObject = (JSONObject) item;
            Map<String, Object> map = new HashMap<>();
            map.put("text", jsonObject.getString("name"));
            map.put("value", jsonObject.getString("id"));

            // 市
            List<Map<String, Object>> children = new ArrayList();
            jsonObject_city.getJSONArray(jsonObject.getString("id")).forEach(item2 -> {
                JSONObject jsonObject2 = (JSONObject) item2;
                Map<String, Object> map2 = new HashMap<>();
                map2.put("text", jsonObject2.getString("name"));
                map2.put("value", jsonObject2.getString("id"));

                // 地区
                List<Map<String, Object>> children2 = new ArrayList();
                JSONArray jsonArray = jsonObject_county.getJSONArray(jsonObject2.getString("id"));
                if (jsonArray == null)
                    return;

                jsonArray.forEach(item3 -> {
                    JSONObject jsonObject3 = (JSONObject) item3;
                    Map<String, Object> map3 = new HashMap<>();
                    map3.put("text", jsonObject3.getString("name"));
                    map3.put("value", jsonObject3.getString("id"));
                    children2.add(map3);
                });

                map2.put("children", children2);
                children.add(map2);
            });

            map.put("children", children);

            result.add(map);
        });

        return Result.OK(result);
    }

    // 只到市
    @SneakyThrows
    @Cacheable(value = "getShengsqxData2")
    @GetMapping(value = "/getShengsqxData2")
    public Result<?> getShengsqxData2() {
        List<Map<String, Object>> result = new ArrayList();

        ClassPathResource classPathResource = new ClassPathResource("area/province.json");
        InputStream inputStream = classPathResource.getInputStream();
        String tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONArray jsonArray_province = JSONArray.parseArray(tmp);

        classPathResource = new ClassPathResource("area/city.json");
        inputStream = classPathResource.getInputStream();
        tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONObject jsonObject_city = JSONObject.parseObject(tmp);

        classPathResource = new ClassPathResource("area/county.json");
        inputStream = classPathResource.getInputStream();
        tmp = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        JSONObject jsonObject_county = JSONObject.parseObject(tmp);

        // 省
        jsonArray_province.forEach(item -> {
            JSONObject jsonObject = (JSONObject) item;
            Map<String, Object> map = new HashMap<>();
            map.put("text", jsonObject.getString("name"));
            map.put("value", jsonObject.getString("id"));

            // 市
            List<Map<String, Object>> children = new ArrayList();
            jsonObject_city.getJSONArray(jsonObject.getString("id")).forEach(item2 -> {
                JSONObject jsonObject2 = (JSONObject) item2;
                Map<String, Object> map2 = new HashMap<>();
                map2.put("text", jsonObject2.getString("name"));
                map2.put("value", jsonObject2.getString("id"));

                children.add(map2);
            });

            map.put("children", children);

            result.add(map);
        });

        return Result.OK(result);
    }

    @GetMapping(value = "/countGroupByDingdzt")
    public Result<?> countGroupByDingdzt(String openId) {
        List<KuybOrder> list = kuybOrderService.list(new LambdaQueryWrapper<KuybOrder>()
                .eq(KuybOrder::getDingdzt, 1)
                .eq(KuybOrder::getOpenId, openId));

        Map map = list.stream().collect(Collectors.groupingBy(KuybOrder::getDingdzt, Collectors.counting()));
        if(map.get("0") ==  null)
            map.put("0", 0);
        if(map.get("1") ==  null)
            map.put("1", 0);
        if(map.get("2") ==  null)
            map.put("2", 0);
        if(map.get("3") ==  null)
            map.put("3", 0);

        return Result.OK(map);
    }

    @GetMapping(value = "/orderTimeline")
    public Result<?> orderTimeline(String zhubId) {
        List result = new ArrayList();

        String dingdbh = "";
        KuybOrder kuybOrder = kuybOrderService.getById(zhubId);
        if (kuybOrder != null) {
            Map map = new HashMap();
            map.put("title", "支付时间");
            map.put("desc", kuybOrder.getCreateTime());
            result.add(map);
            dingdbh = kuybOrder.getDingdbh();
        }

        List<KuybOrderPayment> list = kuybOrderPaymentService.selectByMainId(zhubId);
        if (list != null && list.size() > 0) {
            KuybOrderPayment kuybOrderPayment = list.get(0);
            if (kuybOrderPayment != null) {
                Map map = new HashMap();
                map.put("title", "补充资料");
                map.put("desc", kuybOrderPayment.getCreateTime());
                result.add(map);
            }
        }

        List<KuybOrderPolicy> list2 = kuybOrderPolicyService.selectByMainId(zhubId);
        if (list2 != null && list2.size() > 0) {
            KuybOrderPolicy kuybOrderPolicy = list2.get(0);
            if (kuybOrderPolicy != null) {
                Map map = new HashMap();
                map.put("title", "核保完成");
                map.put("desc", kuybOrderPolicy.getUpdateTime());
                result.add(map);
            }
        }

        if (dingdbh != null) {
            List<KuybOrderShenh> list3 = kuybOrderShenhService.list(new LambdaQueryWrapper<KuybOrderShenh>()
                    .eq(KuybOrderShenh::getDingdbh, dingdbh)
                    .eq(KuybOrderShenh::getShenhjg, 2).orderByDesc(KuybOrderShenh::getCreateTime));
            if (list3 != null && list3.size() > 0) {
                Map map = new HashMap();
                map.put("title", "交易完成");
                map.put("desc", list3.get(0).getCreateTime());
                result.add(map);
            }
        }

        return Result.OK(result);
    }

    @Cacheable(value = "soldList")
    @GetMapping(value = "/soldList")
    public Result<?> soldList() {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String, Object>> subList = new ArrayList<>();

        int count = 0;
        for (KuybJiasj item : kuybJiasjService.list(new LambdaQueryWrapper<KuybJiasj>().orderByDesc(KuybJiasj::getCreateTime).last("limit 1, 99"))
        ) {
            Map<String, Object> map = new HashMap<>();
            map.put("pinp", item.getPinp());
            map.put("chex", item.getChex());
            map.put("beibxr", item.getChez() != null ? item.getChez().substring(0, 1) + "**" : "");
            map.put("chuangjsj", DateUtil.format(item.getCreateTime(), "yyyy-MM-dd"));

            subList.add(map);
            count++;

            if (count % 5 == 0) {
                System.out.println(count);
                Map<String, Object> tmp = new HashMap<>();
                tmp.put("subList", subList);
                result.add(tmp);
                subList = new ArrayList<>();
            }

        }

        return Result.OK(result);
    }

    private String getProductName(String productId) {
        KuybChanp kuybChanp = kuybChanpService.getById(productId);
        if (kuybChanp != null)
            return kuybChanp.getChanpmc();

        return null;
    }

    @SneakyThrows
    @GetMapping(value = "/audit")
    public Result<?> audit(String dingdbh, String auditStatus, String auditMemo) {
        if(auditStatus.equals("2")) {
            KuybOrder kuybOrder = kuybOrderService.getOne(new LambdaQueryWrapper<KuybOrder>().eq(KuybOrder::getDingdbh, dingdbh), false);
            if(kuybOrder != null) {
                List<KuybOrderPolicy> kuybOrderPolicyList = kuybOrderPolicyService.selectByMainId(kuybOrder.getId());
                if(kuybOrderPolicyList != null && kuybOrderPolicyList.size() > 0) {
                    KuybOrderPolicy kuybOrderPolicy = kuybOrderPolicyList.get(0);
                    if(kuybOrder.getUserToken() == null)
                        return Result.error("获取用户签名失败");

                    kuybOrderService.getElectronicPolicy(kuybOrderPolicy.getId(), kuybOrder.getUserToken());
                }
            }
        }

        int rtn = kuybOrderService.audit(dingdbh, auditStatus, auditMemo);
        if (rtn == 0) {
            return Result.OK();
        }
        else
            return Result.error(500, "审核异常: " + rtn);
    }

    @PutMapping(value = "/changeOrderStatus")
    public Result<?> changeOrderStatus(@RequestBody KuybOrder order) {
        KuybOrder kuybOrder = kuybOrderService.getById(order.getId());
        if (kuybOrder == null) {
            return Result.error("未找到对应数据");
        }
        kuybOrder.setDingdzt(order.getDingdzt());
        kuybOrderService.updateById(kuybOrder);

        return Result.OK("编辑成功!");
    }

    @GetMapping(value = "/sendEmail")
    public Result<?> sendEmail(String orderId) {
        KuybOrder kuybOrder = kuybOrderService.getById(orderId);
        if(kuybOrder != null) {
            List<KuybOrderPolicy> kuybOrderPolicyList = kuybOrderPolicyService.selectByMainId(kuybOrder.getId());
            if(kuybOrderPolicyList != null && kuybOrderPolicyList.size() > 0) {
                KuybOrderPolicy kuybOrderPolicy = kuybOrderPolicyList.get(0);
                if(kuybOrderPolicy != null) {
//                    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//                    simpleMailMessage.setFrom("18610348075@163.com");
//                    simpleMailMessage.setTo(kuybOrderPolicy.getBeibxryx());
//                    simpleMailMessage.setSubject("酷延保电子合同");
//                    simpleMailMessage.setText("<a href=\"" + kuybOrderPolicy.getDianzbdxzdz() + "\">电子保单</a>");
//
//                    javaMailSender.send(simpleMailMessage);

                    MimeMessagePreparator preparator = new MimeMessagePreparator() {
                        public void prepare(MimeMessage mimeMessage) throws Exception {
                            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                            message.setTo(kuybOrderPolicy.getBeibxryx());
                            message.setFrom("18610348075@163.com");
                            message.setSubject("酷延保电子合同");

                            message.setText("<a href=\"" + kuybOrderPolicy.getDianzbdxzdz() + "\">点击下载电子保单</a>", true);
                        }
                    };

                    javaMailSender.send(preparator);

                    return Result.OK("电子合同已发送到, " + kuybOrderPolicy.getBeibxryx());
                }
            }
        }

        return Result.error("发送异常");
    }

    /**
     * 分页列表查询
     *
     * @param kuybOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "订单-分页列表查询")
    @ApiOperation(value = "订单-分页列表查询", notes = "订单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(KuybOrder kuybOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<KuybOrder> queryWrapper = QueryGenerator.initQueryWrapper(kuybOrder, req.getParameterMap());

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser != null) {
            if (kuybOrder.getFrom() != null && kuybOrder.getFrom().equals(0))
                queryWrapper.eq("create_by", sysUser.getUsername());
        }

        Page<KuybOrder> page = new Page<KuybOrder>(pageNo, pageSize);
        IPage<KuybOrder> pageList = kuybOrderService.page(page, queryWrapper);
        pageList.getRecords().forEach(item -> {
            List<KuybOrderChanp> kuybOrderChanpList = kuybOrderChanpService.selectByMainId(item.getId());
            item.setKuybOrderChanpList(kuybOrderChanpList);

            if (kuybOrderChanpList != null && kuybOrderChanpList.size() > 0) {
                List<KuybTaoc> kuybTaocList = kuybTaocService.list(new LambdaQueryWrapper<KuybTaoc>().eq(KuybTaoc::getSuoscp, kuybOrderChanpList.get(0).getChanpid()));
                item.setKuybTaocList(kuybTaocList);
            }

            List<KuybOrderPolicy> kuybOrderPolicyList = kuybOrderPolicyService.selectByMainId(item.getId());
            item.setKuybOrderPolicyList(kuybOrderPolicyList);
        });

        return Result.OK(pageList);
    }

    /**
     * 判断两个时间相差多少个月
     *
     * @param form 开始时间
     * @param to   结束时间
     * @return 相差月数
     */
    int differentMonth(Date form, Date to) {
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();
        bef.setTime(form);
        aft.setTime(to);
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
        return Math.abs(month + result);
    }

    String dateAddYear(String date, String year) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cd = Calendar.getInstance();//获取一个Calendar对象
        try {
            cd.setTime(sdf.parse(date));//设置calendar日期
        } catch (ParseException e) {
            e.printStackTrace();
        }

        cd.add(Calendar.YEAR, Integer.parseInt(year));//增加n年

        return sdf.format(cd.getTime());
    }

    String dateAddDay(String date, Integer day) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cd = Calendar.getInstance();//获取一个Calendar对象
        try {
            cd.setTime(sdf.parse(date));//设置calendar日期
        } catch (ParseException e) {
            e.printStackTrace();
        }

        cd.add(Calendar.DATE, day);//增加n年

        return sdf.format(cd.getTime());
    }

    /**
     * 添加
     *
     * @param kuybOrderPage
     * @return
     */
    @AutoLog(value = "订单-添加")
    @ApiOperation(value = "订单-添加", notes = "订单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody KuybOrderPage kuybOrderPage) {
        KuybOrder kuybOrder = new KuybOrder();
        BeanUtils.copyProperties(kuybOrderPage, kuybOrder);

        // 默认自动审核，并且审核通过
        kuybOrder.setShenhfs("1");
        kuybOrder.setShenhjg("2");
        kuybOrder.setDingdzt("0");
        kuybOrder.setDingdbh("ORDER_" + UUID.fastUUID().toString().replaceAll("-", "").substring(0, 8).toUpperCase() + "_" + DateUtil.format(new Date(), "yyyyMMdd") + String.format("_%06d", kuybOrderService.count() + 1));

        KuybOrderPolicy kuybOrderPolicy = kuybOrderPage.getKuybOrderPolicyList().get(0);
        if (kuybOrderPolicy != null) {
            // 大于35、47、59个月的车辆人工核保
            int month = differentMonth(DateUtil.parse(kuybOrderPolicy.getChudrq()), new Date());
            if (month > 35 || month > 47 || month > 59) {
                kuybOrder.setShenhfs("2");
                kuybOrder.setShenhjg("0");
            }

            String goumnx = kuybOrderPolicy.getLevel4Sku().split("\\$")[0];
            String goumgls = kuybOrderPolicy.getLevel4Sku().split("\\$")[1];

            // 起保日期, 行驶里程 > 原厂保修公里数时为当期日期，< 原厂保修公里数时为初登日期+原厂保修年限截止的下一天 00:00:00
            // 终保日期，行驶里程 > 原厂保修公里数时为当期日期 + 产品购买年限，< 原厂保修公里数时为初登日期+原厂保修年限截止的下一天 + 产品购买年限 23:59:59
            String carId = kuybOrderPolicy.getCarid();
            KuybChexkModel kuybChexkModel = kuybChexkModelService.getById(carId);
            if (kuybChexkModel != null) {

                // 原厂质保结束时间
                String yuanczbjssj = dateAddYear(kuybOrderPolicy.getChudrq(), (kuybChexkModel.getYuancbxnx() == null ? 3 : kuybChexkModel.getYuancbxnx()) + "");

                // 行驶里程大于原厂质保公里数，起保时间当前日期+30天，起保公司数当前行驶里程+500公里
                if(kuybChexkModel.getYuancbxgls() == null) {
                    return Result.error("原厂保修公里数异常");
                }

                if (kuybOrderPolicy.getXingslc() > kuybChexkModel.getYuancbxgls()) {
                    String add30Days = dateAddDay(yuanczbjssj, 30);
//                    kuybOrderPolicy.setQibrq(DateUtil.format(kuybOrder.getCreateTime(), "yyyy-MM-dd") + " 00:00:00");
                    kuybOrderPolicy.setQibrq(add30Days + " 00:00:00");
                    kuybOrderPolicy.setZhongbrq(dateAddYear(kuybOrderPolicy.getQibrq(), goumnx) + " 23:59:59");

                    kuybOrderPolicy.setHuiykslc((kuybOrderPolicy.getXingslc() + 500) + "");
                    int tmp = Integer.parseInt(kuybOrderPolicy.getHuiykslc()) + Integer.parseInt(goumgls);
                    kuybOrderPolicy.setHuiyjslc(tmp + "");

                } else {
                    kuybOrderPolicy.setQibrq(yuanczbjssj + " 00:00:00");
                    kuybOrderPolicy.setZhongbrq(dateAddYear(kuybOrderPolicy.getQibrq(), goumnx) + " 23:59:59");
                    kuybOrderPolicy.setHuiykslc((kuybOrderPolicy.getXingslc()) + "");
                    int tmp = Integer.parseInt(kuybOrderPolicy.getHuiykslc()) + Integer.parseInt(goumgls);
                    kuybOrderPolicy.setHuiyjslc(tmp + "");
                }
            }

            // 能源类型纯电混动的截止里程累计至20万公里
            if(kuybOrderPolicy.getNengylx().equals("2") || kuybOrderPolicy.getNengylx().equals("3"))
                kuybOrderPolicy.setHuiyjslc("累计至20万公里");

        }

        kuybOrderService.saveMain(kuybOrder, kuybOrderPage.getKuybOrderPaymentList(), kuybOrderPage.getKuybOrderPolicyList(), kuybOrderPage.getKuybOrderChanpList());

        return Result.OK(kuybOrder);
    }

    /**
     * 编辑
     *
     * @param kuybOrderPage
     * @return
     */
    @SneakyThrows
    @AutoLog(value = "订单-编辑")
    @ApiOperation(value = "订单-编辑", notes = "订单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody KuybOrderPage kuybOrderPage) {
        KuybOrderPolicy kuybOrderPolicy = kuybOrderPage.getKuybOrderPolicyList().get(0);
        if (kuybOrderPolicy != null) {
            String carId = kuybOrderPolicy.getCarid();
            KuybChexkModel kuybChexkModel = kuybChexkModelService.getById(carId);
            if (kuybChexkModel != null) {
                kuybOrderPolicy.setYuancbxnx(kuybChexkModel.getYuancbxnx());
                kuybOrderPolicy.setYuancbxgls(kuybChexkModel.getYuancbxgls());
                kuybOrderPolicy.setZhengczb(kuybChexkModel.getYuancbx());
            }
        }

        KuybOrder kuybOrder = new KuybOrder();
        BeanUtils.copyProperties(kuybOrderPage, kuybOrder);
        KuybOrder kuybOrderEntity = kuybOrderService.getById(kuybOrder.getId());
        if (kuybOrderEntity == null) {
            return Result.error("未找到对应数据");
        }

        // 自动核保
        if(kuybOrder.getShenhfs() != null && kuybOrder.getShenhfs().equals("1")) {
            // 设置成已完成状态
            kuybOrder.setDingdzt("3");
            kuybOrderService.updateMain(kuybOrder, kuybOrderPage.getKuybOrderPaymentList(), kuybOrderPage.getKuybOrderPolicyList(), kuybOrderPage.getKuybOrderChanpList());

            // 生产电子保单
            kuybOrderService.getElectronicPolicy(kuybOrderPage.getKuybOrderPolicyList().get(0).getId(), kuybOrderPage.getUserToken());
        }

        // 人工核保
        if(kuybOrder.getShenhfs() != null && kuybOrder.getShenhfs().equals("2")) {
            // 设置成人工核保状态
            kuybOrder.setDingdzt("4");
            kuybOrderService.updateMain(kuybOrder, kuybOrderPage.getKuybOrderPaymentList(), kuybOrderPage.getKuybOrderPolicyList(), kuybOrderPage.getKuybOrderChanpList());
        }

        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单-通过id删除")
    @ApiOperation(value = "订单-通过id删除", notes = "订单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        kuybOrderService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单-批量删除")
    @ApiOperation(value = "订单-批量删除", notes = "订单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.kuybOrderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单-通过id查询")
    @ApiOperation(value = "订单-通过id查询", notes = "订单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        KuybOrder kuybOrder = kuybOrderService.getById(id);
        if (kuybOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(kuybOrder);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "支付详情通过主表ID查询")
    @ApiOperation(value = "支付详情主表ID查询", notes = "支付详情-通主表ID查询")
    @GetMapping(value = "/queryKuybOrderPaymentByMainId")
    public Result<?> queryKuybOrderPaymentListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<KuybOrderPayment> kuybOrderPaymentList = kuybOrderPaymentService.selectByMainId(id);
        return Result.OK(kuybOrderPaymentList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单和保单通过主表ID查询")
    @ApiOperation(value = "订单和保单主表ID查询", notes = "订单和保单-通主表ID查询")
    @GetMapping(value = "/queryKuybOrderPolicyByMainId")
    public Result<?> queryKuybOrderPolicyListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<KuybOrderPolicy> kuybOrderPolicyList = kuybOrderPolicyService.selectByMainId(id);
        return Result.OK(kuybOrderPolicyList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单和产品通过主表ID查询")
    @ApiOperation(value = "订单和产品主表ID查询", notes = "订单和产品-通主表ID查询")
    @GetMapping(value = "/queryKuybOrderChanpByMainId")
    public Result<?> queryKuybOrderChanpListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<KuybOrderChanp> kuybOrderChanpList = kuybOrderChanpService.selectByMainId(id);
        return Result.OK(kuybOrderChanpList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param kuybOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, KuybOrder kuybOrder) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<KuybOrder> queryWrapper = QueryGenerator.initQueryWrapper(kuybOrder, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<KuybOrder> queryList = kuybOrderService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<KuybOrder> kuybOrderList = new ArrayList<KuybOrder>();
        if (oConvertUtils.isEmpty(selections)) {
            kuybOrderList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            kuybOrderList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<KuybOrderPage> pageList = new ArrayList<KuybOrderPage>();
        for (KuybOrder main : kuybOrderList) {
            KuybOrderPage vo = new KuybOrderPage();
            BeanUtils.copyProperties(main, vo);
            List<KuybOrderPayment> kuybOrderPaymentList = kuybOrderPaymentService.selectByMainId(main.getId());
            vo.setKuybOrderPaymentList(kuybOrderPaymentList);
            List<KuybOrderPolicy> kuybOrderPolicyList = kuybOrderPolicyService.selectByMainId(main.getId());
            vo.setKuybOrderPolicyList(kuybOrderPolicyList);
            List<KuybOrderChanp> kuybOrderChanpList = kuybOrderChanpService.selectByMainId(main.getId());
            vo.setKuybOrderChanpList(kuybOrderChanpList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单列表");
        mv.addObject(NormalExcelConstants.CLASS, KuybOrderPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("订单数据", "导出人:" + sysUser.getRealname(), "订单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<KuybOrderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), KuybOrderPage.class, params);
                for (KuybOrderPage page : list) {
                    KuybOrder po = new KuybOrder();
                    BeanUtils.copyProperties(page, po);
                    kuybOrderService.saveMain(po, page.getKuybOrderPaymentList(), page.getKuybOrderPolicyList(), page.getKuybOrderChanpList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    /**
     * 获取电子保单
     *
     * @return
     */
    @AutoLog(value = "获取电子保单")
    @ApiOperation(value = "获取电子保单", notes = "获取电子保单-通主表ID查询")
    @GetMapping(value = "/getElectronicPolicy")
    public Result<?> getElectronicPolicy(@RequestParam(name = "id", required = true) String id,@RequestParam(name = "userToken", required = true) String userToken ) {
        try {
            kuybOrderService.getElectronicPolicy(id,userToken);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.OK("电子保单生产成功！");
    }
}
